package com.c.ctgproject.http

import com.c.ctgproject.BuildConfig
import com.c.ctgproject.utils.userToken
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import java.io.File

object UpLoadFile {
    /**
     * 通过上传的文件的完整路径生成RequestBody
     *
     * @param imageList 完整的文件路径
     * @return
     */
    private fun getRequestBody(imageList: List<String>, videoList: List<String>, carId: String): RequestBody {
        //创建MultipartBody.Builder，用于添加请求的数据
        val builder = MultipartBody.Builder()
        val headers = Headers.Builder()
        headers.add("token", userToken)
        val body = FormBody.Builder()
        body.add("carId", carId)
        builder.addPart(headers.build(), body.build())

        imageList.forEach {
            val file = File(it) //生成文件
            //根据文件的后缀名，获得文件类型
            builder.addFormDataPart( //给Builder添加上传的文件
                "img",  //请求的名字
                file.name,  //文件的文字，服务器端用来解析的
                RequestBody.create(MediaType.parse("multipart/form-data"), file) //创建RequestBody，把上传的文件放入
            )
        }

        videoList.forEach {
            val file = File(it)
            //根据文件的后缀名，获得文件类型
            builder.addFormDataPart( //给Builder添加上传的文件
                "video",  //请求的名字
                file.name,  //文件的文字，服务器端用来解析的
                RequestBody.create(MediaType.parse("multipart/form-data"), file) //创建RequestBody，把上传的文件放入
            )
        }

        return builder.build() //根据Builder创建请求
    }

    /**
     * 获得Request实例
     *
     * @param url
     * @param fileNames 完整的文件路径
     * @return
     */
    private fun getRequest( fileNames: List<String>, videoList: List<String>, carId: String): Request {
        val builder = Request.Builder()
//        builder.addHeader("token", userToken)
//        val body = FormBody.Builder()
//        body.add("carId", carId)
//        builder.method("POST", body.build())
        builder.url(BuildConfig.SERVER_URL+"/plant/manufacture/uploadPictureAll").post(getRequestBody(fileNames, videoList, carId))
        return builder.build()
    }

    /**
     * 根据url，发送异步Post请求
     * @param imageList 完整的上传的文件的路径名
     * @param callback  OkHttp的回调接口
     */
    fun upLoadFile(imageList: List<String>, videoList: List<String>, carId: String, callback: Callback) {
        val okHttpClient = OkHttpClient()
        val interceptor=HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        okHttpClient.newBuilder().addInterceptor(interceptor)
        val call = okHttpClient.newCall(getRequest( imageList, videoList, carId))
        call.enqueue(callback)
    }
}